// 使用 Express 框架创建一个服务器，实现用户注册和登录功
// 能，使用 JWT 生成登录 token，并验证 token 的有效性。
const express = require("express");
const jwt = require("jsonwebtoken");
const { expressjwt } = require("express-jwt");
const app = express();
const mysql = require("mysql");
const config = {
  jwtSecretKey: "love",
  expiresIn: "80m",
};
const db = mysql.createPool({
  host: "127.0.0.1",
  user: "root",
  password: "root",
  database: "node",
});
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((err, req, res, next) => {
  if (err.name === "UnauthorizedError") {
    return res.send({ code: err.status, msg: err.inner.message });
  }
  next();
});
app.post("/zhuce", (req, res) => {
  if (
    db.query(
      `select * from work where name=${req.body.name}`,
      (err, result) => {
        if (err) return false;
        return true;
      }
    )
  ) {
    res.send({ code: 111, msg: "已有此账号" });
  } else {
    db.query(
      `insert into work(name,password) value("${req.body.name}","${req.body.password})`,
      (err, result) => {
        if (err) return res.send({ code: 111, msg: "注册失败" });
        if (result.affectedRows > 0) {
          return res.send({ code: 999, msg: "注册成功" });
        } else {
          return res.send({ code: 999, msg: "注册失败" });
        }
      }
    );
  }
  // res.send({ code: 999, msg: "注册失败" });
});
app.post("/denglu", (req, res) => {
  db.query(
    `select * from work where name=? and password=?`,
    [req.body.name, req.body.password],
    (err, result) => {
      if (err) return res.send({ code: 0, msg: "失败了" });
      if (result.length === 0) {
        res.send({ code: 0, msg: "登录失败了" });
      } else {
        res.send({ code: 999, msg: "成功" });
      }
      const user = {
        ...result[0],
        password: "",
      };
      const tokenStr = jwt.sign(user, config.jwtSecretKey, {
        expiresIn: config.expiresIn,
      });
      res.send({
        code: 999,
        msg: "登陆成功",
        data: "Bearer " + tokenStr,
      });
    }
  );
});
app.use(
  expressjwt({
    secret: config.jwtSecretKey,
    algorithms: ["HS256"],
  }).unless({
    path: ["/zhuce"],
  })
);
app.listen(3000, () => {
  console.log("启动成功");
});
